package org.jhub1.system.xmpp.commands;

import org.jhub1.system.xmpp.config.ConfigAdapter;
import org.jhub1.system.xmpp.log.LogAdapter;
import org.jhub1.system.xmpp.proxy.ProcessorSession;

public class ElementLogin extends Element implements Executable {

	private static LogAdapter log = LogAdapter.getLog(ElementLogin.class);
	private static ConfigAdapter config = ConfigAdapter.getInstance(log);
	
	public ElementLogin() {
		this.name = "?StartSession";
		this.description = "Starts session (login)";
		this.displayHelp = false;
	}

	@Override
	public ReturnMessage executeCommand(RequestMessage msg) {
		log.debug("Start session command");
		ReturnMessage rm = new ReturnMessage(msg);
		int parNo = msg.getParams().size();
		String passwd = null;
		switch (parNo) {
		case 0:
			rm.setExtStatus(ReturnMessage.REFUSED);
			rm.setMessage(null);
			break;
		case 1:
			passwd = msg.getParams().get(0);
			config.isTrusted(msg);
			if (passwd.equals(config.getSessionPassword()) && config.isTrusted(msg)) {
				if (!ProcessorSession.isActive()) {
					ProcessorSession.startSession(msg.getJid());
					ProcessorSession.setTimeout(15);
					rm.setExtStatus(ReturnMessage.SUCCEEDED);
					rm.setMessage("Session is activated for 15 minutes.");
				}
			} else {
				rm.setExtStatus(ReturnMessage.REFUSED);
				rm.setMessage(null);
			}
			break;
		default:
			passwd = msg.getParams().get(0);
			String stime = msg.getParams().get(1);
			if (passwd.equals("qaz")) {
				int sessionTime;
				if (!ProcessorSession.isActive()) {
					try {
						sessionTime = Integer.parseInt(stime);
					} catch (NumberFormatException e) {
						sessionTime = 15;
					}
					ProcessorSession.startSession(msg.getJid());
					ProcessorSession.setTimeout(sessionTime);
					rm.setExtStatus(ReturnMessage.SUCCEEDED);
					rm.setMessage("Session is activated for " + sessionTime + " minutes.");
				}
			} else {
				rm.setExtStatus(ReturnMessage.REFUSED);
				rm.setMessage(null);
			}
			break;
		}
		return rm;
	}

}
